package top.eggcode.setup.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import top.eggcode.setup.config.ds.SimpleRoutingDataSource;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Configuration
@EnableJpaRepositories(
        // 持久层
        basePackages = {"top.eggcode.system", "top.eggcode.arm.store"},
        entityManagerFactoryRef = "mdsEmFactory",
        transactionManagerRef = "mdsTxManager"
)
public class JpaConfig {

    @Resource(name = "routingDataSource")
    private SimpleRoutingDataSource simpleRoutingDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    /**
     * 将数据源注入实体管理器
     *
     * @param builder 工厂构建器
     * @return 新的实体工厂
     */
    @Primary
    @Bean(name = "mdsEmFactory")
    public LocalContainerEntityManagerFactoryBean userEntityManager(EntityManagerFactoryBuilder builder) {
        Map<String, String> properties = jpaProperties.getProperties();
        //要设置这个属性，实现 CamelCase -> UnderScore 的转换
        properties.put("hibernate.physical_naming_strategy",
                "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");

        return builder
                .dataSource(simpleRoutingDataSource)
                .properties(properties)
                // 实体扫描
                .packages("top.eggcode.system", "top.eggcode.arm.model")
                // 默认数据源
                .persistenceUnit("primary")
                .build();
    }

    /**
     * 将实体工厂注入事务管理器
     *
     * @param builder 新的事务管理器
     * @return
     */
    @Primary
    @Bean(name = "mdsTxManager")
    public PlatformTransactionManager userTransactionManager(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean factoryBean = userEntityManager(builder);
        EntityManagerFactory emFactory = factoryBean.getObject();
        Objects.requireNonNull(emFactory);
        return new JpaTransactionManager(emFactory);
    }
}
